package leetcode.每日一题;

import org.junit.Test;

import java.util.*;

/**
 * @author ：zsy
 * @date ：Created 2021/11/29 9:57
 * @description：https://leetcode-cn.com/problems/find-all-anagrams-in-a-string/
 */
public class 找到字符串中所有字母异位词 {
    @Test
    public void test() {
        Solution solution = new Solution();
        System.out.println(solution.findAnagrams("abab", "ab"));
    }


    class Solution {
        public List<Integer> findAnagrams(String s, String p) {
            List<Integer> ans = new ArrayList<>();
            if (s.length() < p.length()) return ans;
            int[] counts = new int[26];
            int len = p.length();
            for (int i = 0; i < len; i++) {
                counts[p.charAt(i) - 'a']++;
            }
            int[] curCounts = new int[26];
            for (int i = 0; i < len; i++) {
                curCounts[s.charAt(i) - 'a']++;
            }
            for (int i = len; i <= s.length(); i++) {
                boolean flag = true;
                for (int j = 0; j < 26; j++) {
                    if (counts[j] != curCounts[j]) {
                        flag = false;
                        break;
                    }
                }
                if (flag) {
                    ans.add(i - len);
                }
                if (i != s.length()) {
                    curCounts[s.charAt(i - len) - 'a']--;
                    curCounts[s.charAt(i) - 'a']++;
                }
            }
            return ans;
        }
    }
}
